package com.gc.framework.web.base;

import com.gc.common.config.Global;
import com.gc.common.utils.JwtUtil;
import com.gc.common.utils.StringUtils;
import com.gc.common.utils.sql.SqlUtil;
import com.gc.framework.util.ServletUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @title api接口通用数据处理
 * @author huruiyan
 * @date 2019.11.21 15:40
 */
@Repository
public class ApiBaseController {
	
	protected final Logger logger = LoggerFactory.getLogger(ApiBaseController.class);

    String appid = Global.getConfig("ruoyi.wechat_public_appid");
    String appSecret = Global.getConfig("ruoyi.wechat_public_appsecret");
	
	/**
     *   设置请求分页数据  用于移动端调用
     */
    protected void startPage(Integer pageNum,Integer pageSize,String orderByParam)
    {
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize) && StringUtils.isNotEmpty(orderByParam))
        {
            String orderBy = SqlUtil.escapeOrderBySql(orderByParam);
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 公共分页集合设置方法
     * @param pageNum   页数
     * @param pageSize  每页显示数量
     * @param dataList
     * @return
     */
    protected PageInfo getPageList(Integer pageNum, Integer pageSize,List dataList){

        //Null 默认最大99条数据
        Integer pageNumOf = Optional.ofNullable(pageNum).orElse(1).intValue();
        Integer pageSizeOf = Optional.ofNullable(pageSize).orElse(99).intValue();
        //pageHelper分页处理
        Page page = new Page(pageNumOf,pageSizeOf);
        //为Page类中的total属性赋值
        int total = dataList.size();
        //总数
        page.setTotal(total);

        //计算当前需要显示的数据下标起始值
        int startIndex = (pageNumOf - 1) * pageSizeOf;
        int endIndex = Math.min(startIndex + pageSizeOf,total);
        //从链表中截取需要显示的子链表，并加入到Page

        try {
            page.addAll(dataList.subList(startIndex,endIndex));
        }catch (Exception e){
            PageInfo pageInfo = new PageInfo<>(page);
            return pageInfo;
        }

        PageInfo pageInfo = new PageInfo<>(page);
        return pageInfo;
    }

    /**
     * SHA、SHA1加密
     *
     * @param str
     * @return
     */
    public static String SHA1(String str) {
        try {
            MessageDigest digest = MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 构造随机字符串
     *
     * @param length
     * @return
     */
    private static String createNonceStr(int length) {
        String baseStr = "QIAOLIANGUIGUOHUYQIAOABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer temp = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(baseStr.length());
            temp.append(baseStr.charAt(number));
        }
        return temp.toString();
    }
    
    /**
     * @ 全局设置响应头
     */
    protected void responseHeaderPage() {
    	getResponse().setHeader("Access-Control-Allow-Origin", "*");
    	getResponse().setHeader("Cache-Control","no-cache");
    }
    

    /**
     * 获取request
     */
    public HttpServletRequest getRequest()
    {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse()
    {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession()
    {
        return getRequest().getSession();
    }

   
    /**
     * 页面跳转
     * @param url
     * @return
     */
    public String redirect(String url)
    {
        return StringUtils.format("redirect:{}", url);
    }
    
    /**
     * 返回前端:成功通知
     * @return
     */
    public Map<String,Object> success() {
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", "0");
    	map.put("msg", "请求成功");
    	return map;
    }
    
    /**
     * 返回前端:成功通知(自定义消息)
     * @return
     */
    public Map<String,Object> success(String msg) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", "0");
    	map.put("msg", msg);
    	return map;
    }
    
    /**
     * 返回前端：失败方法的通知（自定义code 消息）
     * @param code
     * @param msg
     * @return
     */
    public Map<String,Object> error(int code,String msg){
    	Map<String,Object> map = new HashMap<String,Object>();
    	getResponse().setStatus(code);
    	map.put("code", code);
    	map.put("msg", msg);
    	return map;
    }
    
    /**
     * 返回前端：成功的通知（自定义code 消息）
     * @param code
     * @param msg
     * @return
     */
    public Map<String,Object> success(String code,String msg){
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", code);
    	map.put("msg", msg);
    	return map;
    }
    
    /**
     * 返回前端：成功的通知（自定义code 消息）
     * @param code
     * @param msg
     * @return
     */
    public Map<String,Object> error(String code,String msg){
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", code);
    	map.put("msg", msg);
    	return map;
    }
    
    /**
     * 返回前端：根据条数判断成功/失败
     * @param row
     * @return
     */
    public Map<String,Object> toAjax(int row){
    	return row > 0 ? success() : error(500,"保存失败，请稍后重试！");
    }
    
    /**
     * 返回前端：携带data
     * @param data
     * @return
     */
    public Map<String,Object> success(Object data){
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", "0");
    	map.put("msg", "请求成功！");
    	map.put("data", data);
    	return map;
    }
    
    /**
     * 返回前端：携带data, msg
     * @param data
     * @return
     */
    public Map<String,Object> success(String msg,Object data){
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("code", "0");
    	map.put("msg", msg);
    	map.put("data", data);
    	return map;
    }

    public Long getUserId(String token){
        Claims parseJWT = JwtUtil.parseJWT(token);
        return Long.valueOf((String) parseJWT.get("userId"));
    }

}
